import {
  reqConsumerDeviceMuffling,
  reqDeviceData,
  reqConsumerAlarmPage
} from '../../../../request/api.js'
import {
  showMsg
} from '../../../../utils/config.js'
const app = getApp()
let dictMixin = require('../../../../pages/behaviors/dict/dictMixin.js')

Page({
  behaviors: [dictMixin],
  data: {
    dataList: [{
      id: 0,
      name: '我的家',
    }, {
      id: 2,
      name: '深圳家',
    }, {
      id: 3,
      name: '广州家',
    }, {
      id: 4,
      name: '珠海家',
    }, {
      id: 5,
      name: '佛山家',
    }, ],
    gonzhonghao1: '/statics/images/gaojing/yangan.png',
    roomname: '书房',
    alarmList: [],
    editInfo: {},
    deviceData: {},
    typeName:"",
  },

  onLoad(options) {
    console.log(JSON.parse(options.item), 'options');
    this.setData({
      editInfo: JSON.parse(options.item)
    })
    this.getDict('device_alarm_type');
    this.getDeviceData() // imei查询最新设备数据
    this.getConsumerAlarmPage()  // 告警列表
  },

  onShow() {
    if(app.globalData.deviceInfo!=null){
      console.log(app.globalData.deviceInfo ,'deviceInfo');
      this.setData({
        "editInfo.deviceName":app.globalData.deviceInfo.deviceName,
        "editInfo.roomId":app.globalData.deviceInfo.roomId,
        "editInfo.roomName":app.globalData.deviceInfo.roomName
      })
      app.globalData.deviceInfo =null
      wx.setStorageSync('deviceInfo',null);
    }
  },
  onRecord(){
    wx.navigateTo({
      url: `/packageC/pages/device/alarmRecord/alarmRecord?deviceCode=${this.data.editInfo.deviceCode}`,
    })
  },
  // imei查询最新设备数据
  async getDeviceData() {
    const res = await reqDeviceData(this.data.editInfo.deviceCode)
    if (res.code !== 20000) return showMsg(res.message)
    console.log(res,'imei查询最新设备数据');
    this.setData({
      deviceData: res.data.rows || {}
    })
  },
  
   // 告警列表
    async getConsumerAlarmPage() {
      const res = await reqConsumerAlarmPage(1,50,{
        userId: app.globalData.userId,
        homeId: app.globalData.familyInfo.id,
        deviceCode:this.data.editInfo.deviceCode
      })
      if (res.code !== 20000) return showMsg(res.message)
      console.log(res);
      if(res.data.total==0) return
      // 找到最近的日期的告警数据（最多10条）
      const recentDate = res.data.rows.map(item => item.createTime.split(' ')[0]).reduce((a, b) => (a > b ? a : b)); // 找到最大的日期（最近的日期）
       let recentDate2 = res.data.rows
      .filter(item => item.createTime.startsWith(recentDate))
      .slice(0, 10);
      recentDate2.forEach(item=>{
        item.createTime2=   item.createTime.slice(-8)
        this.data.dictData.forEach(dict => {
          if (item.alarmType == dict.dickValue) {
            item.dickLabel = dict.dickLabel; //告警类型
          }
        })
      })

      this.setData({
        alarmList: recentDate2 || {}
      })
      // 告警状态为告警
      if(this.data.alarmList.length>0 && this.data.editInfo.isAlarm==1){
        let typeName
        this.data.dictData.forEach(dict => {
          if (this.data.alarmList[0].alarmType == dict.dickValue) {
            typeName = dict.dickLabel; //告警类型
          }
        })
        this.setData({
          typeName
        })
      }
    },
  async onErasure() {
    const res = await reqConsumerDeviceMuffling({
      deviceCode: this.data.editInfo.deviceCode
    })
    if (res.code != 20000) return showMsg(res.message)
    showMsg("消音成功", "success")
  },
  goname(item) {
    // console.log(item.currentTarget.dataset.item);
    this.setData({
      roomname: item.currentTarget.dataset.item
    })
  },
  goCreate() {
    wx.navigateTo({
      url: '/packageC/pages/room/add/add',
    })
  },
  goDetail() {
    wx.navigateTo({
      url: '/packageC/family/detail/detail',
    })
  },
  goAdd() {
    wx.navigateTo({
      url: '/packageC/device/nameSet/nameSet',
    })
  },
  onInfo(){
    const mergedData = { 
      ...this.data.deviceData, 
      ...this.data.editInfo 
    };
    let deviceData = JSON.stringify(mergedData)
    wx.navigateTo({
      url: `/packageC/pages/device/deviceInfo/deviceInfo?deviceData=${deviceData}`,
    })
  },

})